#include <stdio.h>

main(unsigned argc, const char *argv[])
{
	if (argc != 2) {
		fprintf(stderr, "Usage: %s INPUT_FILE\n", argv[0]);
		fprintf(stderr, "      INPUT_FILE: For example, multifield.0030.txt\n");
		return -1;
	}

	// Figure out what input file to open and open it.
	const char *input_file_name = argv[1];
	FILE *infile;
	if ( (infile = fopen(input_file_name, "r")) == NULL) {
		fprintf(stderr,"Could not open %s for reading\n", input_file_name);
		return -2;
	}

	// Figure out what output file to open and open it.
	char	output_file_name[4096];
	sprintf(output_file_name, "%s.density.vtk", input_file_name);
	FILE *outfile;
	if ( (outfile = fopen(output_file_name, "w")) == NULL) {
		fprintf(stderr,"Could not open %s for reading\n", output_file_name);
		return -3;
	}

	// Write the header to the output file telling what kind of VTK file
	// this is and what its data set is
	fprintf(outfile, "# vtk DataFile Version 2.0\n");
	fprintf(outfile, "Converted Multifield file density values\n");
	fprintf(outfile, "ASCII\n");
	fprintf(outfile, "DATASET STRUCTURED_POINTS\n");
	fprintf(outfile, "DIMENSIONS 600 248 248\n");
	fprintf(outfile, "SPACING 0.001 0.001 0.001\n");
	fprintf(outfile, "ORIGIN 0 0 0\n");
	fprintf(outfile, "POINT_DATA 36902400\n");
	fprintf(outfile, "SCALARS density float 1\n");
	fprintf(outfile, "LOOKUP_TABLE default\n");

	// Scan each input line, grab the density data, and write it to the output
	unsigned long l;
	float	density, temperature, ab_H, ab_HP, ab_He, ab_HeP, ab_HePP, ab_HM, ab_H2, ab_H2P;
	for (l = 0; l < 36902400; l++) {
		if (fscanf(infile, "%f %f %f %f %f %f %f %f %f %f",
		   &density, &temperature,
		   &ab_H, &ab_HP, &ab_He, &ab_HeP, &ab_HePP, &ab_HM, &ab_H2, &ab_H2P) != 10) {
			fprintf(stderr,"Could not read line %ld\n", l);
			return -4;
		}
		if (fprintf(outfile, "%0.3E\n", density) < 0) {
			fprintf(stderr,"Could not write line %ld\n", l);
			return -5;
		}
	}

	fclose(infile);
	fclose(outfile);

	return 0;
}

